package com.ruoyi.cbs.contract.services;

import com.ruoyi.cbs.approval.config.ApprovalConstant;
import com.ruoyi.cbs.approval.domain.vo.StartInstanceReqVO;
import com.ruoyi.cbs.approval.services.ApprovalServices;
import com.ruoyi.cbs.contract.domain.*;
import com.ruoyi.cbs.contract.domain.vo.*;
import com.ruoyi.cbs.contract.service.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.project.ApprovalStatusEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdFactory;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContractorServices {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ApprovalServices approvalServices;
    @Autowired
    private IContractorService contractorService;
    @Autowired
    private IContractorDocumentService contractorDocumentService;
    @Autowired
    private IContractorEquipmentService contractorEquipmentService;
    @Autowired
    private IContractorPersonnelService contractorPersonnelService;
    @Autowired
    private IContractorInsuranceService contractorInsuranceService;
    @Autowired
    private ContractorPersonnelServices contractorPersonnelServices;


    /**
     * 查询承包商列表
     * @return
     */
    public List<ContractorSelectVo> selectContractorList(String contractorName, String status) {
        Contractor searchEntity = new Contractor();
        searchEntity.setIsBlack("0");
        searchEntity.setStatus(status);
        searchEntity.setContractorName(contractorName);
        List<Contractor> contractorList = contractorService.selectContractorList(searchEntity);

        List<ContractorSelectVo> contractorSelectVoList = new ArrayList<>();
        for (Contractor contractor : contractorList) {
            ContractorSelectVo contractorSelectVo = new ContractorSelectVo();
            BeanUtils.copyProperties(contractor, contractorSelectVo);
            contractorSelectVo.setContractorId(contractor.getId());
            contractorSelectVoList.add(contractorSelectVo);
        }
        return contractorSelectVoList;
    }


    /**
     * 查询承包商详情
     * @param contractorId
     * @return
     */
    public ContractorVo getContractorDetail(String contractorId) {
        if (StringUtils.isEmpty(contractorId)) {
            return null; // 或抛出异常，根据业务需求
        }
        // 查询承包商基本信息
        Contractor contractor = contractorService.selectContractorById(Long.valueOf(contractorId));
        if (contractor == null) {
            return null; // 或抛出异常，根据业务需求
        }
        ContractorVo contractorVo = new ContractorVo();
        BeanUtils.copyProperties(contractor, contractorVo);
        contractorVo.setContractorId(contractor.getId());

        // 初始化承包商资料列表
        List<ContractorDocument> documentList = contractorDocumentService.selectListByContractorId(Long.valueOf(contractorId));
        List<ContractorDocumentVo> documentVoList = new ArrayList<>();
        for (ContractorDocument document : documentList) {
            ContractorDocumentVo documentVo = new ContractorDocumentVo();
            BeanUtils.copyProperties(document, documentVo);
            documentVo.setDocumentId(document.getId());
            documentVoList.add(documentVo);
        }
        contractorVo.setDocumentlList(documentVoList);

        // 初始化设备列表
        List<ContractorEquipmentVo> equipmentList = new ArrayList<>();
        for (ContractorEquipment equipment : contractorEquipmentService.selectListByContractorId(Long.valueOf(contractorId))) {
            ContractorEquipmentVo equipmentVo = new ContractorEquipmentVo();
            BeanUtils.copyProperties(equipment, equipmentVo);
            equipmentVo.setEquipmentId(equipment.getId());
            equipmentList.add(equipmentVo);
        }
        contractorVo.setEquipmentList(equipmentList);

        // 初始化人员列表
        List<ContractorPersonnelVo> personnelList = contractorPersonnelServices.selectListByContractorId(new Long(contractorId));
        contractorVo.setPersonnelList(personnelList);

        // 返回包含所有字段的ContractorVo对象（空值字段会自然保留null）
        return contractorVo;
    }

    /**
     * 新建承包商
     * @param contractorVo
     * @return
     */
    @Transactional
    public boolean createContractor(ContractorVo contractorVo) {
        boolean flag = saveContractor(contractorVo);
        return flag ? addSysUser(contractorVo.getContractorName(), contractorVo.getContactPhone()) : false;
    }

    /**
     * 新建承包商——创建承包商基本信息
     * @param contractorVo
     * @return
     */
    @Transactional
    public boolean saveContractor(ContractorVo contractorVo) {
        Contractor contractor = new Contractor();
        BeanUtils.copyProperties(contractorVo, contractor);
        contractorService.insertContractor(contractor);

        // 获取保存后的承包商ID（用于关联子表数据）
        Long contractorId = contractor.getId();

        // 承包商保险信息
        ContractorInsurance insurance = contractorVo.contractorVoToInsurance(contractorVo);
        if (insurance != null) {
            insurance.setContractorId(contractorId);
            contractorInsuranceService.insertContractorInsurance(insurance);
        }

        // 2. 保存设备列表
        if (contractorVo.getEquipmentList() != null) {
            for (ContractorEquipmentVo equipmentVo : contractorVo.getEquipmentList()) {
                ContractorEquipment equipment = new ContractorEquipment();
                BeanUtils.copyProperties(equipmentVo, equipment);
                equipment.setContractorId(contractorId); // 关联承包商ID
                equipment.setContractorName(contractorVo.getContractorName());
                equipment.setValidityEnd(DateUtils.parseDate(equipmentVo.getValidityEnd()));
                equipment.setValidityStart(DateUtils.parseDate(equipmentVo.getValidityStart()));
                contractorEquipmentService.insertContractorEquipment(equipment);
            }
        }

        // 3. 保存人员列表
        if (contractorVo.getPersonnelList() != null) {
            contractorPersonnelServices.addContractorPersonnel(contractorVo.getPersonnelList(),
                    contractorId, contractorVo.getContractorName());
        }

        // 4. 保存文档列表
        if (contractorVo.getDocumentlList() != null) {
            for (ContractorDocumentVo documentVo : contractorVo.getDocumentlList()) {
                ContractorDocument document = new ContractorDocument();
                BeanUtils.copyProperties(documentVo, document);
                document.setContractorId(contractorId); // 关联承包商ID
                document.setContractorName(contractorVo.getContractorName());
                contractorDocumentService.insertContractorDocument(document);
            }
        }

        return true;
    }


    /**
     * 申请审核承包商准入信息
     *
     * @param contractor
     * @return
     */
    @Transactional
    public boolean submitAdmitApproval(Contractor contractor) {
        // 更新承包商状态为“待审核”
        contractor.setStatus("1");
        contractorService.updateContractor(contractor);

        StartInstanceReqVO vo = StartInstanceReqVO.builder()
                .targetId(contractor.getId())
                .targetName(contractor.getContractorName())
                .targetType(ApprovalConstant.TARGET_TYPE_CONTRACTOR)
                .approvalType(ApprovalConstant.APPROVAL_TYPE_ACCESS)
                .requireSign("1")
                .build();
        int taskTotal = approvalServices.startApprovalInstance(vo);

        return taskTotal > 0;
    }

    /**
     * 保存审核结果——承包商准入
     * @param contractorId
     * @param approvalStatus
     * @return
     */
    @Transactional
    public boolean saveAdmitApprovalResult(Long contractorId, String approvalStatus) {
        // 审核通过
        String passStatus = "3";
        // 审核退回修改
        String rejectStatus = "2";
        // 更新承包商状态
        Contractor contractor = contractorService.selectContractorById(contractorId);
        contractor.setStatus(ApprovalStatusEnum.APPROVED.getCode().equals(approvalStatus) ? passStatus : rejectStatus);
        contractorService.updateContractor(contractor);

        // 审核通过，给承包商人员创建系统用户账号
        if (rejectStatus.equals(contractor.getStatus())) {
            return true;
        }

        ContractorPersonnel searchPersonnel = new ContractorPersonnel();
        searchPersonnel.setContractorId(contractorId);
        List<ContractorPersonnel> contractorPersonnelList = contractorPersonnelService.selectContractorPersonnelList(searchPersonnel);
        if (contractorPersonnelList != null && contractorPersonnelList.size() > 0) {
            for (ContractorPersonnel personnel : contractorPersonnelList) {
                SysUser sysUser = new SysUser();
                sysUser.setNickName(personnel.getName());
                sysUser.setUserName(personnel.getPhone());
                sysUser.setSex(personnel.getSex());
                sysUser.setPhonenumber(personnel.getPhone());
                sysUser.setAvatar(personnel.getPhoto());
                sysUser.setStatus("0");
                sysUser.setRemark(contractor.getContractorName() + "准入申请通过后给承包商人员开通系统账号");
                // 保存系统用户
                Long userId = saveSysUser(sysUser);

                if (userId != null) {
                    // 保存承包商人员与系统用户关联关系
                    ContractorPersonnel updateEnty = new ContractorPersonnel();
                    updateEnty.setId(personnel.getId());
                    updateEnty.setUserId(userId);
                    contractorPersonnelService.updateContractorPersonnel(updateEnty);
                }
            }
        }

        return true;
    }


    /**
     * 新建承包商——创建登录账号业务
     * @param contractorName
     * @param tel
     * @return
     */
    @Transactional
    public boolean addSysUser(String contractorName, String tel) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(tel);
        sysUser.setNickName(contractorName);
        sysUser.setRemark(contractorName + "发起准入申请开通的账号");
        sysUser.setPhonenumber(tel);
        Long userId = saveSysUser(sysUser);
        return userId != null;
    }

    @Transactional
    public Long saveSysUser(SysUser sysUser) {
        sysUser.setUserId(IdFactory.newLongId());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setCreateTime(new Date());
        sysUser.setCreateBy("sys");
        // 添加用户角色
        sysUser.setRoleId(70l);
        sysUser.setStatus("0");
        sysUser.setDelFlag("0");
        sysUser.setRoleIds(new Long[]{70L});
        int r = userService.insertUser(sysUser);

        return r>0 ? sysUser.getUserId() : null;
    }

}
